package com.learn.hibernatevalidator.chapter06.crossparameter;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.constraintvalidation.SupportedValidationTarget;
import jakarta.validation.constraintvalidation.ValidationTarget;

import java.util.Date;

/**
 * 用于检查方法的两个 `Date` 参数是否按正确的顺序排列：
 *
 * @author: liyf
 * @create: 2025-01-15 23:17
 **/

/**
 * 必须加上这个注解：否则会发生：jakarta.validation.ConstraintDeclarationException: HV000132: Void methods must not be constrained or marked for cascaded validation, but method CalendarService#createCalendarEvent(Date, Date) is. 异常
 */
@SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class ConsistentDateParametersValidator
        implements ConstraintValidator<ConsistentDateParameters, Object[]> {

    @Override
    public void initialize(ConsistentDateParameters constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Object[] value, ConstraintValidatorContext context) {
        if (value.length != 2) {
            throw new IllegalArgumentException("Illegal method signature");
        }

        //leave null-checking to @NotNull on individual parameters
        if (value[0] == null || value[1] == null) {
            return true;
        }

        if (!(value[0] instanceof Date) || !(value[1] instanceof Date)) {
            throw new IllegalArgumentException(
                    "Illegal method signature, expected two parameters of type Date."
            );
        }

        return ((Date) value[0]).before((Date) value[1]);
    }
}
